import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {View, Button, Picker} from '@tarojs/components'
import {AtInput, AtIcon, AtAvatar} from 'taro-ui'
import {http} from '../../../utils/http'
import {vcmonitor, GetRequest} from "../../../utils/tools";
import {
  VERIFIER_TELLER_SAVE,
  VERIFIER_TELLER_UPDATE,
  VERIFIER_SELLER_USER,
  VERIFIER_FIND_USER,
  GETSUPPLIERSTORELISTBYSUPPLIERID
} from '../../../constants/api'
import {user} from '../../../utils/user.service'
import Headercar from "../../components/header-car/header-car";
import GzhAuth from "../../../components/gzh-auth/gzh-auth";
import NewSwitch from "../../productForm/components/switch"
import './add.scss'

export default class Setting extends Component {
  state: {
    shopList: any
    user_info: any
    shopShow: boolean
    userInfo: any
    checkIndex: number
    detail: any
    storeList: any
    storeIndex: any
    userId: any
    supplier_id: any
  } = {
    shopList: [],
    shopShow: false,
    user_info: {},
    userInfo: [],
    checkIndex: 0,
    detail: {},
    storeList: [],
    storeIndex: 0,
    userId: null,
    supplier_id: null
  }

  async UNSAFE_componentWillMount() {
    // 获取门店
    const {detail} = this.state;
    const query: any = Taro.getCurrentInstance().router.params;
    const supplier_id = query.id;
    const userId = query.userId;
    detail.supplier_id = supplier_id;
    if (userId) {
      this.setState({
        userId,
        supplier_id
      }, () => this.closeSlide(true));
    }
    const res = await http.HPost(GETSUPPLIERSTORELISTBYSUPPLIERID, {
      supplier_id
    });
    const storeList = res.data.list;
    this.setState({
      storeList,
      detail
    });
  }

  async componentDidShow() {
    vcmonitor(this)
    const isLogin = await user.checkLogin()
    if (!isLogin) {
      Taro.showToast({
        title: '你还未登录，请登录',
        icon: 'none',
      })
      const timer = setTimeout(() => {
        clearTimeout(timer)
        user.jumpLogin()
      }, 1500)
      return
    }
  }

  // input输入
  inputChange(value) {
    const user_info: any = this.state.user_info;
    user_info.q = value;
    this.setState({
      user_info
    });
  }

  // 点击选择
  async findUser() {
    if (!this.state.user_info.q) {
      Taro.showToast({title: '请输入关键词', mask: true, icon: 'none'})
      return
    }
    Taro.showLoading({title: '加载中...'});
    const res = await http.HGet(VERIFIER_SELLER_USER, {q: this.state.user_info.q})
    if (res) {
      if (res.data && res.data.length > 0) {
        const userInfo = res.data.map(item => ({
          value: item.id,
          label: item.text
        }));
        this.setState({
          userInfo,
          shopShow: true
        }, () => {
          Taro.hideLoading();
          this.closeSlide(0)
        });
      } else {
        Taro.hideLoading();
        this.setState({
          detail: {
            address: '',
            checker_group_id: '',
            is_super: '',
            name: '',
            sex: '',
            storeName: '',
            supplier_id: '',
            is_super: '',
            storeName: '',
            url: '',
            user_id: '',
          }, userInfo: [], shopShow: false})
      }
    }
  }

  // 用户滑动时触发
  async onSlide({detail: value}) {
    this.setState({
      checkIndex: value.value
    });
    this.closeSlide(value.value)
  }

  // 关闭或选择用户
  async closeSlide(checkIndex) {
    let { userInfo, detail, supplier_id, userId} = this.state;
    supplier_id = supplier_id || '';
    let user_id = userId
    if (userInfo && userInfo.length > 0) {
      user_id = userInfo[checkIndex].value
    }
    const res = await http.HGet(VERIFIER_FIND_USER, {
      user_id,
      supplier_id
    });
    detail = {
      ...detail,
      name: res.data.nick_name,
      url: res.data.photo,
      sex: res.data.gender == 1 ? '男' : res.data.gender == 2 ? '女' : '',
      address: res.data.address,
      user_id: res.data.id
    };
    if (userId) {
      detail.is_super = res.data.supplierUserModel.is_super;
      detail.storeName = res.data.supplierUserModel.group_name || '';
      detail.checker_group_id = res.data.checker_group_id || '';
    }
    this.setState({
      detail
    });
  }

  // 选择门店
  onStoreChange({detail: {value}}) {
    const {storeList, detail} = this.state;
    const storeDetail = storeList[value];
    detail.storeName = storeDetail.name;
    detail.checker_group_id = storeDetail.id;
    this.setState({
      storeIndex: value,
      detail
    })
  }

  // 提交
  async submit() {
    const {detail, userId} = this.state;
    Taro.showLoading({title: '加载中...'});
    let api;
    if (!userId) {
      // 新增
      api = VERIFIER_TELLER_SAVE;
    } else {
      // 编辑
      api = VERIFIER_TELLER_UPDATE;
    }
    const res = await http.postCar(api, detail);
    if (!res) {
      return;
    }
    Taro.hideLoading();
    Taro.navigateBack({
      delta: 1
    });
  }

  render() {
    const {storeIndex, shopShow, userInfo, detail, storeList, user_info,checkIndex} = this.state;
    return (
      <View className='my-setting-root'>
        <GzhAuth />
        <View className='head-bg' style='height:60Px;background:#fff'>
          <Headercar color='#333' title='核销员管理' />
        </View>
        <View className='user-box'>
          <View className='flex'>
            <AtInput
              title='筛选用户'
              placeholder='输入昵称/手机号/姓名'
              onChange={this.inputChange.bind(this)}
              value={user_info.q}
            />
            <View className='check' onClick={() => this.findUser()}>搜索</View>
          </View>
          {shopShow && <Picker mode='selector' range={userInfo} rangeKey='label' onChange={this.onSlide.bind(this)}>
            <View className='goaddlist face_list'>
              <View className='label face_label'>
                选择用户
              </View>
              <View
                className='face_right'
                style={userInfo[checkIndex] ? 'color: #000;' : 'color: #c5c5c5;'}
              >
                {userInfo[checkIndex].label}
              </View>
            </View>
          </Picker>}
          <View className='goaddlist face_list flex'>
            <View className='label face_label'>
              是否超级核销员
            </View>
            <View
              className='face_right'
              style={detail.storeName ? 'color: #000;' : 'color: #c5c5c5;'}
            >
              <NewSwitch
                color={process.env.mainColor}
                onChange={(value) => {
                  detail.is_super = value == true ? 1 : 0;
                  this.setState({
                    detail
                  });
                }}
                isCheck={detail.is_super == 1}
              />
            </View>
          </View>
          <View className='header-img'>
            <View className='header-title'>头像</View>
            <View className='img-box'>
              <AtAvatar image={detail.url} />
            </View>
          </View>
          <View className='goaddlist face_list'>
            <View className='label face_label'>
              昵称
            </View>
            <View className='face_right'>
              {detail.name || ''}
            </View>
          </View>
          <View className='goaddlist face_list'>
            <View className='label face_label'>
              性别
            </View>
            <View className='face_right'>
              {detail.sex}
            </View>
          </View>
          <View className='goaddlist face_list'>
            <View className='label face_label'>
              地区
            </View>
            <View className='face_right'>
              {detail.address || ''}
            </View>
          </View>
          <Picker
            value={storeIndex}
            range={storeList}
            rangeKey='name'
            onChange={this.onStoreChange.bind(this)}
            mode='selector'
          >
            <View className='goaddlist face_list'>
              <View className='label face_label'>
                选择门店
              </View>
              <View
                className='face_right'
                style={detail.storeName ? 'color: #000;' : 'color: #c5c5c5;'}
              >
                {detail.storeName || '请选择门店'}
                <AtIcon value='chevron-right' size='16' color='#c5c5c5'></AtIcon>
              </View>
            </View>
          </Picker>
        </View>
        <View className='cancel-after-management-add'>
          <Button onClick={() => this.submit()} className='cancel-after-management-add-btn'
            style={`background: ${process.env.mainColor};`}
          >
            提交信息
          </Button>
        </View>
      </View>
    )
  }
}
